package com.bestcem.xm.cjm.grpc.client;

import com.bestcem.bp.xm.user.grpc.v1.services.*;
import com.bestcem.xm.cjm.convert.grpc.CjmGrpcConvertMapper;
import com.bestcem.xm.cjm.grpc.client.dto.UserDto;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.component.cache.annotation.XmCache;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class UserGrpcClient {

    @GrpcClient(GrpcClientNames.DS_USER)
    private UserServiceGrpc.UserServiceBlockingStub userServiceBlockingStub;

    @GrpcClient(GrpcClientNames.DS_USER)
    private OrgServiceGrpc.OrgServiceBlockingStub orgServiceBlockingStub;

    @GrpcClient(GrpcClientNames.DS_USER)
    private UserGroupServiceGrpc.UserGroupServiceBlockingStub userGroupServiceBlockingStub;

    private final CjmGrpcConvertMapper grpcConvertMapper;

    public UserGrpcClient(CjmGrpcConvertMapper grpcConvertMapper) {
        this.grpcConvertMapper = grpcConvertMapper;
    }

    @XmCache
    public UserDto getUser(String userId) {
        GetUserByIdRequest.Builder builder = GetUserByIdRequest.newBuilder();
        builder.setId(userId);
        try {
            GetUserByIdResponse response = userServiceBlockingStub.getUserById(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[cjm] USER getUser {} Error; ErrorMsg: {}", userId, response);
                return null;
            }
            return responseToUserDTO(response);
        } catch (Exception e) {
            log.error("[cjm] USER getUser {} Error; ErrorMsg: {}", userId, e.getMessage(), e);
            return null;
        }
    }

    private UserDto responseToUserDTO(GetUserByIdResponse response) {
        User user = response.getUser();
        return grpcConvertMapper.toUserDto(user);
    }
}
